<template>
  <div>
    <!-- 动态表格 -->
    <template v-if="loader">
      <my-table stripe border highlight-current-row align="center" size="medium" :columns="columns" :loader="load"
        :page="page" :page-size="pageSize"
        :pagination="{background:true,layout:'total,sizes, ->, prev, pager, next',pageSizes: [5, 10, 30, 50, 100],prevText:' 上一页 ',nextText:' 下一页 '}">
        <slot></slot>
      </my-table>
    </template>
    <!-- 静态表格 -->
    <template v-else>
      <my-table stripe border highlight-current-row align="center" size="medium" :columns="columns" :data="list">
        <slot></slot>
      </my-table>
      <el-pagination background :layout="'total,sizes, ->, prev, pager, next'" @size-change="handleSizeChange"
        :page-sizes='[5, 10, 30, 50, 100]' @current-change="handleCurrentChange" :current-page="currentPage"
        :prev-text="'上一页'" :next-text="'下一页'" :page-size="currentPageSize" :total="currentTotal"
        style="padding-top: 12px;">
      </el-pagination>
    </template>
  </div>
</template>
<script>
  export default {
    props: {
      // 表格数据
      data: {
        type: Array,
        default () {
          return []
        }
      },
      // 列配置
      columns: {
        type: Array,
        default () {
          return []
        }
      },
      // 初始页码
      page: {
        type: Number,
        default: 1
      },
      // 初始页大小
      pageSize: {
        type: Number,
        default: 10
      },
      // 加载数据函数
      loader: Function
    },
    data: function() {
      return {
        list: [],
        currentPage: this.page,
        currentTotal: 0,
        currentPageSize: this.pageSize,
      }
    },
    mounted: function() {},
    methods: {
      //加载数据
      async load(page, pageSize) {
        var res = await this.loader(page, pageSize);
        return {
          total: res.data.length,
          list: this.getPageList(page, pageSize, res.data),
        };
      },
      //手动分页-获取指定页数据
      getPageList(page, pageSize, list) {
        var startIndex = (page - 1) * pageSize;
        return list.slice(startIndex, startIndex + pageSize);
      },
      //加载静态表格数据
      loadStaticData() {
        this.currentTotal = this.data.length;
        this.list = this.getPageList(this.currentPage, this.currentPageSize, this.data);
      },
      handleSizeChange(pageSize) {
        this.currentPageSize = pageSize
        this.currentPage = 1
        this.loadStaticData()
      },
      handleCurrentChange(page) {
        this.currentPage = page
        this.loadStaticData()
      },
    },
    watch: {
      data() {
        if (this.loader == undefined) {
          this.loadStaticData();
        }
      }
    }
  }
</script>

<style>
</style>
